<?php

namespace zhtfrontend\models\datas;
use common\components\extenders\MenuManage;
use yii\rbac\Rule;

/**
 * Created by PhpStorm.
 * User: dongxiaofeng
 * Date: 2018/1/2
 * Time: 10:59
 */
class AuthRule extends \zhtfrontend\components\bases\BaseModel {
    /**
     * @var string name of the rule
     */
    public $name;

    /**
     * @var integer UNIX timestamp representing the rule creation time
     */
    public $createdAt;

    /**
     * @var integer UNIX timestamp representing the rule updating time
     */
    public $updatedAt;

    /**
     * @var string Rule classname.
     */
    public $className;

    /**
     * @var Rule
     */
    private $_item;

    public $operate;

//    public function __construct($config=[]){
//
//    }

    //不根据数据库表
    public function __construct($item, $config = [])
    {
        $this->_item = $item;
        if ($item !== null) {
            $this->name = $item->name;
            $this->className = get_class($item);
        }
        $this->operate = (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
        parent::__construct($config);
    }

    public function rules()
    {
        return [
            [['name','className'],'required'],
            ['name','unique'],
            ['className','string'],
            ['className','class_exists']
        ];
    }

    public function class_exists($attribute)
    {
        if (!class_exists($this->className)) {
            $message = "Unknown class ".$this->className;
            $this->addError($attribute, $message);
            return;
        }
        if (!is_subclass_of($this->className, Rule::className())) {
            //$message = Yii::t('rbac-admin', "'{class}' must extend from 'yii\rbac\Rule' or its child class", [
            //    'class' => $this->className]);
            $message = $this->className." must extend from 'yii\\rbac\\Rule' or its child class";
            $this->addError($attribute, $message);
        }
    }

    public function attributeLabels()
    {
        return [
            'name' => '规则名称',
            'className' => '规则对应的类路径',
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['name'] = $this->name;
        $fields['className'] = $this->className;
        return $fields;
    }

    public function save($runValidation = true, $attributeNames = null)
    {
        if ($runValidation) {
            if($this->validate()){
                $manager = \Yii::$app->authManager;
                $class = $this->className;
                if ($this->_item === null) {
                    $this->_item = new $class();
                    $isNew = true;
                } else {
                    $isNew = false;
                    $oldName = $this->_item->name;
                }
                $this->_item->name = $this->name;

                if ($isNew) {
                    $manager->add($this->_item);
                } else {
                    $manager->update($oldName, $this->_item);
                }

                return true;
            }else {
                return false;
            }

        } else {
            $manager = \Yii::$app->authManager;
            $class = $this->className;
            if ($this->_item === null) {
                $this->_item = new $class();
                $isNew = true;
            } else {
                $isNew = false;
                $oldName = $this->_item->name;
            }
            $this->_item->name = $this->name;

            if ($isNew) {
                $manager->add($this->_item);
            } else {
                $manager->update($oldName, $this->_item);
            }

            return true;
        }
    }

    public function attributes()
    {
        $attributes = parent::attributes(); // TODO: Change the autogenerated stub
        $attributes[] = 'name';$attributes[] = 'className';
        return $attributes;
    }

    public function extraFields()
    {
        $extraFields['operate'] = function () {
            return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
        };
        return $extraFields;
    }
}